package com.lwj.mallchat.common.user.service.impl;

import com.lwj.mallchat.common.common.annotation.RedissonLock;
import com.lwj.mallchat.common.common.event.UserBlackEvent;
import com.lwj.mallchat.common.common.event.UserRegisterEvent;
import com.lwj.mallchat.common.common.utils.AssertUtil;
import com.lwj.mallchat.common.user.dao.BlackDao;
import com.lwj.mallchat.common.user.dao.ItemConfigDao;
import com.lwj.mallchat.common.user.dao.UserBackpackDao;
import com.lwj.mallchat.common.user.dao.UserDao;
import com.lwj.mallchat.common.user.domain.dto.ItemInfoDTO;
import com.lwj.mallchat.common.user.domain.dto.SummeryInfoDTO;
import com.lwj.mallchat.common.user.domain.entity.*;
import com.lwj.mallchat.common.user.domain.enums.BlackTypeEnum;
import com.lwj.mallchat.common.user.domain.enums.ItemEnum;
import com.lwj.mallchat.common.user.domain.enums.ItemTypeEnum;
import com.lwj.mallchat.common.user.domain.vo.req.user.BlackReq;
import com.lwj.mallchat.common.user.domain.vo.req.user.ItemInfoReq;
import com.lwj.mallchat.common.user.domain.vo.req.user.SummeryInfoReq;
import com.lwj.mallchat.common.user.domain.vo.resp.user.BadgeResp;
import com.lwj.mallchat.common.user.domain.vo.resp.user.UserInfoResp;
import com.lwj.mallchat.common.user.service.UserService;
import com.lwj.mallchat.common.user.service.adapter.UserAdapter;
import com.lwj.mallchat.common.user.service.cache.ItemCache;
import com.lwj.mallchat.common.user.service.cache.UserCache;
import com.lwj.mallchat.common.user.service.cache.UserSummaryCache;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lwj
 * @ClassName UserServiceImpl
 * @date 2024/10/17 16:23
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserBackpackDao userBackpackDao;

    @Autowired
    private ItemCache itemCache;

    @Autowired
    private ItemConfigDao itemConfigDao;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Autowired
    private BlackDao blackDao;

    @Autowired
    private UserCache userCache;

    @Autowired
    private UserSummaryCache userSummaryCache;

    @Override
    @Transactional
    public Long register(User user) {
        userDao.save(user);
        //todo 用户注册事件
        applicationEventPublisher.publishEvent(new UserRegisterEvent(this, user));
        return user.getId();
    }

    @Override
    public UserInfoResp getUserInfo(Long uid) {
        User user = userDao.getById(uid);
        Integer modifyNameCount = userBackpackDao.countByValidItemId(uid, ItemEnum.MODIFY_NAME_CARD.getId());
        UserInfoResp userInfoResp = new UserInfoResp();
        BeanUtils.copyProperties(user, userInfoResp);
        return UserAdapter.buildUserInfo(user, modifyNameCount);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @RedissonLock(key = "#uid")
    public void modifyName(Long uid, String name) {
        User user = userDao.getByName(name);
        AssertUtil.isEmpty(user, "名字已经被抢占，请再换一个~");
        UserBackpack modifyNameItem = userBackpackDao.getFirstValidItem(uid, ItemEnum.MODIFY_NAME_CARD.getId());
        AssertUtil.isNotEmpty(modifyNameItem, "改名卡不够了，等后续活动送改名卡吧");
        boolean success = userBackpackDao.useItem(modifyNameItem.getId());
        if (success) {
            userDao.modifyName(uid, name);
        }
    }

    @Override
    public List<BadgeResp> getBadgesById(Long uid) {
        //查询所有徽章
        List<ItemConfig> itemConfigs = itemCache.getByType(ItemTypeEnum.BADGE.getType());
        //查询用户拥有徽章
        List<UserBackpack> userBackpacks = userBackpackDao.getByItemIds(uid, itemConfigs.stream().map(ItemConfig::getId).collect(Collectors.toList()));
        //查询用户佩戴的徽章
        User user = userDao.getById(uid);
        return UserAdapter.buildBadgesResp(itemConfigs, userBackpacks, user);
    }

    @Override
    public void wearBadge(Long uid, Long itemId) {
        //确保有徽章
        UserBackpack firstValidItem = userBackpackDao.getFirstValidItem(uid, itemId);
        AssertUtil.isNotEmpty(firstValidItem, "你还没有获得这个徽章，快去获得吧");
        //确保物品是徽章
        ItemConfig itemConfig = itemConfigDao.getById(itemId);
        AssertUtil.equal(itemConfig.getType(), ItemTypeEnum.BADGE.getType(), "只有徽章才能佩戴");
        //佩戴徽章
        boolean b = userDao.wearBadge(firstValidItem.getUid(), itemId);
    }

    @Override
    public void black(BlackReq blackReq) {
        Long uid = blackReq.getUid();
        //锁id
        blackUid(uid);
        User user = userDao.getById(uid);
        //锁ip
        blackIp(Optional.ofNullable(user.getIpInfo()).map(IpInfo::getCreateIp).orElse(null));
        blackIp(Optional.ofNullable(user.getIpInfo()).map(IpInfo::getUpdateIp).orElse(null));
        applicationEventPublisher.publishEvent(new UserBlackEvent(this, user));
    }

    @Override
    public List<SummeryInfoDTO> getSummeryUserInfo(SummeryInfoReq req) {
        //需要前端同步的uid
        List<Long> uidList = getNeedSyncUidList(req.getReqList());
        //加载用户信息
        Map<Long, SummeryInfoDTO> batch = userSummaryCache.getBatch(uidList);
//        System.out.println("hello");
        return req.getReqList()
                .stream()
                .map(a -> batch.containsKey(a.getUid()) ? batch.get(a.getUid()) : SummeryInfoDTO.skip(a.getUid()))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    private List<Long> getNeedSyncUidList(List<SummeryInfoReq.infoReq> reqList) {

        List<Long> needSyncUidList = new ArrayList<>();
        List<Long> userModifyTime = userCache.getUserModifyTime(reqList.stream().map(SummeryInfoReq.infoReq::getUid).collect(Collectors.toList()));
        for (int i = 0; i < reqList.size(); i++) {
            SummeryInfoReq.infoReq infoReq = reqList.get(i);
            Long modifyTime = userModifyTime.get(i);
            if (Objects.isNull(infoReq.getLastModifyTime()) || (Objects.nonNull(modifyTime) && modifyTime > infoReq.getLastModifyTime())) {
                needSyncUidList.add(infoReq.getUid());
            }
        }
        return needSyncUidList;
    }

    @Override
    public List<ItemInfoDTO> getItemInfo(ItemInfoReq req) {
        return req.getReqList().stream().map(a -> {
            ItemConfig itemConfig = itemCache.getById(a.getItemId());
            if (Objects.nonNull(a.getLastModifyTime()) && a.getLastModifyTime() >= itemConfig.getUpdateTime().getTime()) {
                return ItemInfoDTO.skip(a.getItemId());
            }
            ItemInfoDTO dto = new ItemInfoDTO();
            dto.setItemId(itemConfig.getId());
            dto.setImg(itemConfig.getImg());
            dto.setDescribe(itemConfig.getDescribe());
            return dto;
        }).collect(Collectors.toList());

    }

    private void blackUid(Long uid) {
        Black black = new Black();
        black.setType(BlackTypeEnum.UID.getType());
        black.setTarget(uid.toString());
        try {
            //存在id重复的情况，抛出的异常不需要处理
            blackDao.save(black);
        } catch (Exception e) {

        }
    }

    private void blackIp(String ip) {
        if (Objects.isNull(ip))
            return;
        Black black = new Black();
        black.setType(BlackTypeEnum.IP.getType());
        black.setTarget(ip);
        try {
            //存在ip重复的情况，抛出的异常不需要处理
            blackDao.save(black);
        } catch (Exception e) {

        }
    }
}
